import * as types from './ActionTypes';
import StorageManager, {
  USER_INFO,
  METAMASK_ADDRESS,
  GAME_LIST,
  DID_SHOW_ROOM_LEAD,
} from '../../storage';
import {getChainConfig} from '../../api/chain';
import {query, logout, queryNotifyAmountForUnread} from '../../api/user';
import {queryGames} from '../../api/game';
import WalletUtils from '../../utils/wallet/WalletUtils';
import store from '../store';
import {BASE_API} from '../../config';
import {compare} from '../../utils/tools';
//异步action
export const updateUserInfo = (userInfo) => async (dispatch) => {
  try {
    console.log('参数中的user' + JSON.stringify(userInfo));

    if (!userInfo) {
      let info = await StorageManager.load(USER_INFO);
      if (info) {
        console.log('本地存储的info' + JSON.stringify(info));
        let results = await Promise.all([
          query({userToken: info.token}),
          queryNotifyAmountForUnread({userToken: info.token}),
        ]);
        console.log('更新用户信息');
        console.log(results);

        userInfo = results[0].data;
        userInfo.unreadMessageAmount = results[1].data.amount;
        // userInfo.disableGift = true;
      } else {
        return new Promise((resolve) => {
          dispatch({
            type: types.UPDATE_USER_INFO,
            userInfo: null,
          });
          resolve(userInfo);
        });
      }
    }

    delete userInfo.address;
    delete userInfo.keystore;

    console.log('userinfo' + JSON.stringify(userInfo));

    let walletInfo = await StorageManager.load(METAMASK_ADDRESS);
    console.log(walletInfo);
    walletInfo = JSON.parse(walletInfo);

    return new Promise((resolve) => {
      dispatch({
        type: types.UPDATE_USER_INFO,
        userInfo: {
          ...userInfo,
          metamaskAddress: walletInfo?.address || null,
          // metamaskToken: walletInfo?.token || null,
          image:
            userInfo?.image.indexOf('http') != -1
              ? userInfo.image
              : BASE_API + userInfo.image,
        },
      });
      resolve(userInfo);
    });
  } catch (err) {
    console.log('身份验证失败');
    console.log(err);
    return null;
  }
};

export function clearRoomData() {
  console.log('清除房间数据');

  //用dispathch包裹起来
  return (dispatch) => {
    try {
      dispatch(setCurrentRoom(null));
      dispatch(setCurrentRoomListener([]));
      dispatch(setCurrentRoomSpeaker([]));
      dispatch(setCurrentRoomOfflineUsers([]));
      dispatch(setCurrentRoomChatDatas([]));
    } catch (err) {
      console.log('清除数据错误');
    }
  };
}

//查询链的配置和支持发礼物的coin列表
export const queryChainConfig = (userToken) => async (dispatch) => {
  try {
    let response = await getChainConfig();
    console.log('------queryChainConfig');
    console.log(response);

    //初始化钱包工具
    WalletUtils.initWeb3(response.data.node.url);

    return dispatch({
      type: types.CHAIN_CONFIG,
      data: {
        ...response.data,
        config: response.data.node,
        symbol: response.data.gasCoin.symbol,
        swapSymbol: response.data.gasCoin.swapSymbol,
        coins: response.data.coins.map((item) => {
          return {
            ...item,
            icon: BASE_API + item.icon,
          };
        }),
      },
    });
  } catch (err) {
    console.log('查询链的配置信息失败' + err);
    return null;
  }
};

export function setCurrentChainId(chainId) {
  return {
    type: types.UPDATE_CHAIN_ID,
    data: {
      currentChainId: chainId,
    },
  };
}

//设置当前房间聊天内容
export function setCurrentRoomChatDatas(datas) {
  return {
    type: types.CURRENT_ROOM_CHAT_DATA,
    datas,
  };
}

//设置当前房间
export function setCurrentRoom(room) {
  if (room) {
    room.isCommonRoom = room.owner == 99999;
  }

  return {
    type: types.CURRENT_ROOM,
    room,
  };
}

//设置当前房间静音用户
export function setCurrentRoomMuteUser(users) {
  console.log('设置用户');
  console.log(users);

  return {
    type: types.ROOM_MUTE_USERT,
    users,
  };
}

//设置房间key
export function setRoomKey(key) {
  //保持home页面出来的后的第一个页面的key
  let roomKey = store.getState().Layout.roomKey;
  if (roomKey != '' && key != '') {
    key = roomKey;
  }

  console.log('设置roomkey' + key);

  return {
    type: types.SET_ROOM_KEY,
    key,
  };
}

//设置当前房间有声音的用户
export function setRoomSpeakingUsers(users) {
  return {
    type: types.ROOM_SPEAKING_USERS,
    users,
  };
}

//设置当前房间开麦用户
export function setCurrentRoomSpeaker(users) {
  console.log('排序前的数组' + JSON.stringify(users));
  //排序
  users.sort(compare('joinChannelDate'));

  console.log('排序后的数组' + JSON.stringify(users));

  return {
    type: types.CURRENT_ROOM_SPEAKER,
    users,
  };
}

//设置当前房间
export function setCurrentRoomListener(users) {
  // console.log('排序前的听众数组' + JSON.stringify(users));
  //排序
  users.sort(compare('joinChannelDate'));

  // console.log('排序后的听众数组' + JSON.stringify(users));

  return {
    type: types.CURRENT_ROOM_LISTENER,
    users,
  };
}

//设置当前房间的举手用户
export function setCurrentRoomRaisedUsers(users) {
  console.log('设置举手的用户数组为：' + JSON.stringify(users));
  return {
    type: types.ROOM_RAISE_HAND_USERS,
    users,
  };
}

//设置当前通话控制控件布局样式
export function setRoomWidgetLayout(layout) {
  return {
    type: types.ROOM_WIDGET_LAYOUT,
    layout,
  };
}

//路由
export function setRoutersStack(navState) {
  try {
    var routes = navState.routes[navState.index].routes;
  } catch (err) {
    console.log('导航栈解析错误');
  }
  console.log(routes);
  return {
    type: types.ROUTER_STACK,
    stack: routes ? routes : [],
  };
}

// //添加当前房间离线用户
// export function addCurrentRoomOfflineUsers(user) {
//   return {
//     type: types.CURRENT_ROOM_OFFLINEUSER,
//     data: {
//       type: 'add',
//       user,
//     },
//   };
// }

// //删除当前房间离线用户
// export function deleteCurrentRoomOfflineUsers(user) {
//   return {
//     type: types.CURRENT_ROOM_OFFLINEUSER,
//     data: {
//       type: 'delete',
//       user,
//     },
//   };
// }

export function setCurrentRoomOfflineUsers(users) {
  return {
    type: types.CURRENT_ROOM_OFFLINEUSER,
    data: {
      users,
    },
  };
}

//异步action
export const userLogout = () => async (dispatch) => {
  try {
    let info = await StorageManager.load(USER_INFO);
    await logout({userToken: info.token});
    StorageManager.remove(USER_INFO);
    StorageManager.remove(DID_SHOW_ROOM_LEAD);

    return dispatch({
      type: types.UPDATE_USER_INFO,
      userInfo: {},
    });
  } catch (err) {
    console.log('身份验证失败');
    console.log(err);
    return null;
  }
};

//更新钱包余额信息
export const queryWalltBalance = () => async (dispatch) => {
  try {
    //初始化钱包工具
    let ownerAddress = store.getState().User.userInfo.metamaskAddress;
    let newCoins = [...store.getState().Chain.coins];

    console.log('token列表');
    console.log(newCoins);

    let balances = await Promise.all(
      newCoins.map((item) => {
        if (item.isErc20) {
          return WalletUtils.queryTokenBalance(
            ownerAddress,
            item.contractAddress,
            18,
          );
        } else {
          return WalletUtils.queryAccountHecoBalance(ownerAddress);
        }
      }),
    );
    balances.map((item, idx) => {
      return (newCoins[idx].balance = item);
    });

    // console.log(newCoins);

    return dispatch({
      type: types.UPDATE_WALLET_BALANCE,
      coins: newCoins,
    });
  } catch (err) {
    console.log('更新钱包余额失败' + err);
    return null;
  }
};

//查询游戏列表
export const queryGameList = () => async (dispatch) => {
  try {
    let info = await StorageManager.load(GAME_LIST);
    let result = await queryGames();

    console.log('查询的游戏列表' + JSON.stringify(result));
    console.log(info);

    let games = result.data.map((item) => {
      return {
        ...item,
        needUpdate: true,
        progress: undefined,
        showText: '',
      };
    });

    if (info) {
      JSON.parse(info).map((item) => {
        let {name, version} = item;
        games.forEach((item) => {
          if (item.name == name && item.version == version) {
            item.needUpdate = false;
          }
        });
      });
    }

    //根据本地存储的下载信息，更新最新的下载

    return dispatch({
      type: types.GAME_LIST,
      games: games,
    });
  } catch (err) {
    console.log('查询游戏列表失败');
    console.log(err);
    return null;
  }
};

export const updateGameInfo = (info) => {
  let games = store.getState().Game.games;

  let newGames = games.map((item) => {
    if (item.name == info.name) {
      return {
        ...item,
        ...info,
      };
    } else {
      return item;
    }
  });

  return {
    type: types.GAME_LIST,
    games: newGames,
  };
};
